package com.ruoyi.scheduleTask

import cn.hutool.core.date.DateUtil
import com.ruoyi.back.enums.UserTypeEnum
import com.ruoyi.back.service.AppUserService
import com.ruoyi.back.service.UserMemberService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.util.*

@Component
@EnableScheduling
class UserMemberTask {

    @Autowired
    private lateinit var appUserService: AppUserService

    @Autowired
    private lateinit var userMemberService: UserMemberService

    @Scheduled(cron = "0 0/10 * * * ?")
    fun task() {

        userMemberService.list()
            .takeIf { it.isNotEmpty() }
            ?.run {
                forEach {

                    if (DateUtil.compare(Date(), it.endMemberDate) > 0) {
                        appUserService.getById(it.createBy)?.let { appUser ->
                            appUserService.updateById(appUser.apply {
                                userType = UserTypeEnum.EXPIRE_MEMBER.code
                            })
                        }
                    }
                }
            }
    }
}